package com.k2.exstrasensorytypredictor;

import java.io.IOException;
import java.io.StreamCorruptedException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.k2.exstrasensorytypredictor.containers.GfxResourceContainer;
import com.k2.exstrasensorytypredictor.containers.UserPoints;
import com.k2.exstrasensorytypredictor.controls.MButton;
import com.k2.exstrasensorytypredictor.controls.Sprite;
import com.k2.exstrasensorytypredictor.dialogs.IOnDialogButtonPressed;
import com.k2.exstrasensorytypredictor.dialogs.MDialog;
import com.k2.exstrasensorytypredictor.interfaces.IConstants;
import com.k2.exstrasensorytypredictor.interfaces.ITouchHandler;

public class MainScreen extends Activity implements ITouchHandler, IOnDialogButtonPressed, IConstants {

	private MButton[] buttons;
	
	RelativeLayout layout;
	//AbsoluteLayout al;
	RelativeLayout.LayoutParams params;
	
	private float koeffX;
	private float koeffY;
	
	private int rateStarts = 0;
	private int action;
	private int startTime = 0;
	private boolean isNeedToRate = true;
	private boolean isTrialMode = true;
	
	private Matrix m;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
    	rateStarts = pref.getInt("rate_starts", 0);
    	isNeedToRate = pref.getBoolean("need_rate", true);
    	startTime = pref.getInt("start_time", 0);
    	if (isTrialMode && ++startTime >= TRIAL_PERIOD){
    		System.exit(0);
    	}
    	
    	
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        try {
			initUI();
		} catch (IOException e) {
			e.printStackTrace();
		}
        initLaout();
        if(isNeedToRate && ++rateStarts >= RATE_PERIOD){
        	Log.d("RATE_DEBUG", "RATE!!!");
    		action = RATE;
    		int a = (new MDialog(MainScreen.this, MainScreen.this,
					DIALOG_TEXTS[0][12], new String[] { DIALOG_TEXTS[0][9],
							DIALOG_TEXTS[0][10] }, false, MDialog.DIALOG_YES_NO)
					.showDialog());
    	}
        if ((UserPoints.getInstance() == null || !UserPoints.getInstance().isUsersAreSet()) && action != RATE) {
			setUsers();
			//        showMsg(String.valueOf(layout.getWidth()) + "x" + String.valueOf(layout.getHeight()));
		}
    }
    
    private void initUI() throws IOException{
    	this.koeffX = (float)getWindowManager().getDefaultDisplay().getWidth() / SCREEN_RES_X;
    	this.koeffY = (float)getWindowManager().getDefaultDisplay().getHeight() / SCREEN_RES_Y;
    	layout = new RelativeLayout(this);
//    	{
//    		@Override
//    		protected void onDraw(Canvas canvas) {
//    			drawBmp(canvas);
//    			super.onDraw(canvas);
//    		}
//    	};
    	
    	buttons = new MButton[BUTTONS_COORDINATES.length];
    	Log.d("add_buttons", String.valueOf(buttons.length));
    	for (int i = 0; i < BUTTONS_COORDINATES.length; i++){
    		buttons[i] = new MButton(this, new Bitmap[]{GfxResourceContainer.getInstance(this).getmScreenButtonBg()[i][0],
    				GfxResourceContainer.getInstance(this).getmScreenButtonBg()[i][1]}, i, true);
    	}
    }

    private void initLaout() {
    	
    	params = new RelativeLayout.LayoutParams((int)(SCREEN_RES_X * this.koeffX), (int)(SCREEN_RES_Y * this.koeffY));
    	setContentView(layout, params);
    	layout.setBackgroundDrawable(GfxResourceContainer.getInstance(this).getMainBgMs());
    	
    	for (int i = 0; i < this.buttons.length; i++) {
    		params = new RelativeLayout.LayoutParams((int)buttons[i].getBtnWidth(), (int)buttons[i].getBtnHeight());//btn.getBtnWidth(), btn.getBtnHeight()
            params.leftMargin = (int)(BUTTONS_COORDINATES[i][0] * this.koeffX);
            params.topMargin = (int)(BUTTONS_COORDINATES[i][1] * this.koeffY);
            
            layout.addView(buttons[i], params);
		}
    	
//    	Sprite s = new Sprite(this, GfxResourceContainer.getInstance(this).getMainText(), new float[]{0.52f, this.koeffY});
//    	params = new RelativeLayout.LayoutParams((int)s.getSpriteWidth(), (int)s.getSpriteHeight());//btn.getBtnWidth(), btn.getBtnHeight()
//        params.leftMargin = (int)(textCoordinates[6][0] * this.koeffX);
//        params.topMargin = (int)(textCoordinates[6][1] * this.koeffY);
//    	
//    	layout.addView(s, params);
	}

//	@Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.activity_main, menu);
//        return true;
//    }

	public void showMsg(String str){
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		Log.d("mActivity", str);
	}

	@Override
	public boolean onAreaTouched(View view, MotionEvent event) {
		Log.d("btn touch hnd", ((MButton)view).getName() + "pressed...");
		switch (((MButton)view).getId()) {
		case NUM_SCREEN_ID:
			UserPoints.getInstance().setDefaultActiveUser();
			startActivity(new Intent(this, NumScreen.class));
			break;
		case CARD_SCREEN_ID:
			UserPoints.getInstance().setDefaultActiveUser();
			startActivity(new Intent(this, CardsScreen.class));
			break;
		case COLOR_SCREEN_ID:
			UserPoints.getInstance().setDefaultActiveUser();
			startActivity(new Intent(this, ColorScreen.class));
			break;
		case PICTURE_SCREEN_ID:
			UserPoints.getInstance().setDefaultActiveUser();
			startActivity(new Intent(this, PictScreen.class));
			
			break;
		case GEOMETRY_SCREEN_ID:
			UserPoints.getInstance().setDefaultActiveUser();
			startActivity(new Intent(this, GeometryScreen.class));
			
			break;
		case MORE_GAMES_BUTTON_ID:
			Intent brw = new Intent(Intent.ACTION_VIEW, Uri.parse(MORE_GAMES_URL));
			startActivity(brw);
			
			break;

		default:
			break;
		}
		//exit();
		return false;
	}
	
	@Override
	public void onBackPressed() {
		this.action = EXIT;
		int a = (new MDialog(MainScreen.this, MainScreen.this, DIALOG_TEXTS[0][5], new String[]{DIALOG_TEXTS[0][9], DIALOG_TEXTS[0][10]}, false, MDialog.DIALOG_YES_NO)).showDialog();
			
	}

	@Override
	public void OnDialogButtonPressed(int message) {
		switch (action) {
		case RATE:
			if(message == MDialog.ANSWER_YES){
				//start browser or market intent for rate
				Intent brw = new Intent(Intent.ACTION_VIEW, Uri.parse(MORE_GAMES_URL));
				startActivity(brw);
				isNeedToRate = false;
				//=======================================
			} else if (message == MDialog.ANSWER_NO){
				rateStarts = 0;
			}
			setUsers();
			break;
		case EXIT:
			if (message == MDialog.ANSWER_YES){
				UserPoints.getInstance().resset();
				SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = pref.edit();
				editor.putBoolean("need_rate", isNeedToRate);
				editor.putInt("start_time", startTime);
				editor.putInt("rate_starts", rateStarts);
				editor.commit();
//				finish();
				System.exit(0);
			}
			break;
		case SET_USERS:
			if(message == MDialog.ANSWER_YES){
				UserPoints.getInstance(1).addUser(DIALOG_TEXTS[0][2]);
			} else if(message == MDialog.ANSWER_NO){
				UserPoints.getInstance(2).addUser(DIALOG_TEXTS[0][2]);
			}
			break;

		default:
			break;
		}
	}
	
	private void setUsers(){
		action = SET_USERS;
		this.action = SET_USERS;
		int a = (new MDialog(MainScreen.this, MainScreen.this,
				DIALOG_TEXTS[0][1], new String[] { DIALOG_TEXTS[0][7],
						DIALOG_TEXTS[0][8] }, false, MDialog.DIALOG_YES_NO)
				.showDialog());
	}
}
